global class EngineerHandoverHandler {

	///通知 接手的工程师
	WebService static String toComfirm( String eId  ){
		EngineerHandover__c eh = [select Id,Status__c,Owner.Name   from EngineerHandover__c where Id=:eId ];
		
		if(eh.Status__c == '审批中' || eh.Status__c == '已批准') return '已通知确认,请不要重复操作!';
		List<Task> tL = new List<Task>();
		Set<Id> users = new Set<Id>();
		for (HandoverDetails__c hd : [select Id ,MasterTable__c ,ReceivingPerson__c from HandoverDetails__c
			 where  MasterTable__c =:eId  ] ) {

			if(hd.ReceivingPerson__c != null )users.add(hd.ReceivingPerson__c);
			
		}

		Map<Id,Id> userMap = new Map<Id,Id>();
		for(EngineerHandover__Share eshare :[select Id ,UserOrGroupId from EngineerHandover__Share where ParentId=:eId and UserOrGroupId in:users ]){

			userMap.put(eshare.UserOrGroupId, eshare.Id );
		}
		List<EngineerHandover__Share> esList  = new List<EngineerHandover__Share>();
		for (Id uid  : users ) {

			EngineerHandover__Share es = new EngineerHandover__Share();
			es.UserOrGroupId = uid;
			es.ParentId = eId;
			es.AccessLevel = 'Read';
			es.Id = userMap.get(uid);
			esList.add(es);


			Task t = new Task();
			t.WhatId = eId;
			t.Subject = eh.Owner.Name +'工作交接需要您处理';
			t.OwnerId = uid;
			t.Description = eh.Owner.Name +'工作交接需要您处理';
			t.ActivityDate = System.today();
			t.Priority = 'Normal';
			tl.add(t);
		}
		SavePoint sp = Database.setSavepoint();
		try {
			
			List<HandoverDetails__c> hl = new LIst<HandoverDetails__c>();
			for (HandoverDetails__c hd  :[select Id ,ConfirmHandover__c  from HandoverDetails__c where MasterTable__c =: eId  ] ) {
				hd.ConfirmHandover__c =false;
				hl.add(hd);
			}
			eh.Status__c = '审批中';
			update hl;
			if(!tl.isEmpty())insert tL;
			if(!esList.isEmpty()) upsert esList;

			update eh ;
			try {
			    Approval.lock(eh,false);
			}catch (Exception e) {}
			
		    return '通知成功!';
		}catch (Exception e) {
		    Database.rollback(sp);
		    return '通知失败:'+e.getMessage();
		}

	

	}

	//接手的工程师确认后自动提交审批
	public static void autoCommit(List<HandoverDetails__c> list_new,Map<Id,HandoverDetails__c>oldMap  ){

		Map<Id,HandoverDetails__c> msets = new Map<Id,HandoverDetails__c>();
		for ( HandoverDetails__c hd : list_new ) {
			HandoverDetails__c old = oldMap.get(hd.Id);
			if(hd.ConfirmHandover__c == true && old.ConfirmHandover__c != true ){

				msets.put(hd.MasterTable__c,hd );
			}
		}

		for (HandoverDetails__c hd : [select Id ,MasterTable__c from HandoverDetails__c
			 where ConfirmHandover__c != true and  MasterTable__c in:msets.keyset() ] ) {
			
			if(msets.containsKey(hd.MasterTable__c))msets.remove(hd.MasterTable__c);
		}
		if(msets.isEmpty())return;

		for(Id  hdId  : msets.keySet() ){

		   update new EngineerHandover__c(Id=hdId,Status__c = '审批中');  

			Approval.ProcessSubmitRequest req1 =new Approval.ProcessSubmitRequest();
		        req1.setObjectId(hdId);
		       // req1.setSubmitterIdhd.OwnerId);
		        Approval.ProcessResult result = Approval.process(req1);
		        if(result != null && !result.isSuccess() && result.getErrors().size()> 0){
		        	Database.Error  e = result.getErrors()[0];
		        	msets.get(hdId).addError('提交审批失败:'+e.getMessage());
		        }
		}

		
	}
	///审批通过后 1.生成配件还回申请 2.根据配件接手工程师生成配件借出申请
	public static void generateNewBill(List<EngineerHandover__c> list_new,Map<Id,EngineerHandover__c> oldMap ){

		Set<Id> hdList = new Set<Id>();
		for (EngineerHandover__c hd :  list_new) {
			EngineerHandover__c old = oldMap.get(hd.Id);
			//审批通过
			if(hd.Status__c == '已批准' && old.Status__c != hd.Status__c ){
				hdList.add(hd.Id );
			}
			
		}
		if(hdList.isEmpty())return;
		
		//交接主表 + 公司
		//还回申请
		Map<String,PartsReturn__c> reMainMap = new Map<String,PartsReturn__c>();
		Map<String,List<PartsReturnDetails__c>> reDetailMap = new Map<String,List<PartsReturnDetails__c>>();
		
		//交接主表 + 公司+ 接收工程师
		//借出申请
		Map<String,PartsLendingApplication__c> leMainMap = new Map<String,PartsLendingApplication__c>();
		Map<String,List<PartsLendingDetails__c>> leDetailMap = new Map<String,List<PartsLendingDetails__c>>();

		for (HandoverDetails__c hdd  :[select Id ,Quantity__c,Product__c,PartsLendingDetails__c,MasterTable__r.OwnerId,
			ReceivingPerson__c,
		 	PartsLendingDetails__r.PartsLendingApplication__r.InventoryOrganization__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.InvoicingCustomers__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.TerminalClient__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.ReceivingRemarks__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.Phone__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.PhysicalDelivery__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.DocumentTypes__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.FollowupProcessing__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.Remark__c ,
		 	PartsLendingDetails__r.PartsLendingApplication__r.InstallmentSale__c 


		 from HandoverDetails__c where MasterTable__c in:hdList ] ) {
			
			String key = hdd.MasterTable__c+hdd.PartsLendingDetails__r.PartsLendingApplication__r.InventoryOrganization__c;


			//还回申请
			if(!reMainMap.containsKey(key))reMainMap.put(key,new PartsReturn__c(
												Company__c=hdd.PartsLendingDetails__r.PartsLendingApplication__r.InventoryOrganization__c,
												OwnerId = hdd.MasterTable__r.OwnerId,
												NotificationAssistantTime__c = System.today(),
												WorkHandover__c = hdd.MasterTable__c


												//Company__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.InventoryOrganization__c
											));
			
			List<PartsReturnDetails__c> tmp = reDetailMap.containsKey(key) ? reDetailMap.get(key) : new List<PartsReturnDetails__c>();
			
			PartsReturnDetails__c pd = new PartsReturnDetails__c();
			pd.Parts__c = hdd.PartsLendingDetails__c ;

			pd.ReturnQuantity__c = hdd.Quantity__c;
			pd.ReturnAccessories__c = hdd.Product__c;

			tmp.add(pd);
			if(!reDetailMap.containsKey(key))reDetailMap.put(key, tmp);

			String lendkey = key + hdd.ReceivingPerson__c;

			//借出申请
			if(!leMainMap.containsKey(lendkey))leMainMap.put(lendkey,new PartsLendingApplication__c(
												InventoryOrganization__c=hdd.PartsLendingDetails__r.PartsLendingApplication__r.InventoryOrganization__c,
												OwnerId = hdd.ReceivingPerson__c,
												NotificationAssistant__c= System.today(),
												WorkHandover__c = hdd.MasterTable__c,
												InvoicingCustomers__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.InvoicingCustomers__c,
												TerminalClient__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.TerminalClient__c,
												
												ReceivingRemarks__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.ReceivingRemarks__c,
												Phone__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.Phone__c,
												PhysicalDelivery__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.PhysicalDelivery__c,
												DocumentTypes__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.DocumentTypes__c,
												FollowupProcessing__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.FollowupProcessing__c,
												Remark__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.Remark__c,
												InstallmentSale__c = hdd.PartsLendingDetails__r.PartsLendingApplication__r.InstallmentSale__c

											));


			List<PartsLendingDetails__c> letmp = leDetailMap.containsKey(lendkey) ? leDetailMap.get(lendkey) : new List<PartsLendingDetails__c>();
			
			PartsLendingDetails__c pld = new PartsLendingDetails__c();
			pld.No__c = hdd.Quantity__c;
			pld.Product__c = hdd.Product__c;

			letmp.add(pld);
			if(!leDetailMap.containsKey(lendkey))leDetailMap.put(lendkey, letmp);
		}
		System.debug('EngineerHandoverHandler==>'+reMainMap);
		insert reMainMap.values();
		

		List<PartsReturnDetails__c> tmp1 = new List<PartsReturnDetails__c>();
		for (String key :  reMainMap.keySet() ) {
			
			for(PartsReturnDetails__c pd: reDetailMap.get(key)){
				pd.PartsReturn__c = reMainMap.get(key).Id;
				tmp1.add(pd);
			}
		}
		if(!tmp1.isEmpty())insert tmp1;


		insert leMainMap.values();
		
		List<PartsLendingDetails__c> tmp2 = new List<PartsLendingDetails__c>();
		for (String key :  leMainMap.keySet() ) {
			
			for(PartsLendingDetails__c pd: leDetailMap.get(key)){
				pd.PartsLendingApplication__c = leMainMap.get(key).Id;
				tmp2.add(pd);
			}
		}
		if(!tmp2.isEmpty())insert tmp2;
		Approval.lock(leMainMap.values(),false );
		Approval.lock(reMainMap.values(),false );




	}



    
}